<?php
/**
 * Created by 项目.
 * User: xuguopeng
 * Date: 6/21/21
 * Time: 9:21 PM
 */

namespace app\api\controller\v1;


use app\api\model\Store;
use app\api\model\StoreUser as StoreUserModel;
use app\api\model\UserMoney as UserMoneyModel;
use app\api\model\ProductOrder;
use app\api\model\User;

class AdminRankList
{
    /**
     * 余额明细
     *  1. 根据用户类型判断
     *  2. 可以根据店员 团员 进行查询
     */
    public function getUserMoneyList($start_time,$end_time,$id,$store_user_id,$store_id)
    {
        $where = [];
        if(!$start_time){
            $start_time = strtotime("-1 month");
            $end_time = time();
            $where[] = ['user_money.create_time', 'egt', $start_time];
            $where[] = ['user_money.create_time', 'elt', $end_time];
        } else {
            $where[] = ['user_money.create_time', 'egt', strtotime($start_time." 00:00:00")];
            $where[] = ['user_money.create_time', 'elt', strtotime($end_time." 23:59:59")];
        }
        if($id != -1) {
            if($store_user_id) {
                $storeUsers = StoreUserModel::where('id',$store_user_id)
                    ->select()->toArray();
            }else{
                $storeUsers = StoreUserModel::where('store_id',$id)
                    ->select()->toArray();
            }
            $ids = array_column($storeUsers,'user_id');
            $whereOne = $where;
            $whereOne[] = ['user_id','in',$ids];
            $whereOne[] = ['type','eq',1];
            return UserMoneyModel::where($whereOne)->with('user')
                ->order('create_time desc')
                ->select()->each(function ($item){
                    $item['store_user'] = StoreUserModel::where('user_id',$item['user_id'])->find();
                    $item['product_order'] = ProductOrder::with('user')->where('id',$item['order_id'])->find();
                })->toArray();
        } else {
            $whereOne = $where;
            $whereOne[] = ['user_money.user_type','eq',1];
            $whereOne[] = ['user_money.type','eq',1];
            return UserMoneyModel::hasWhere('user', function($query) use($store_id){
                    if($store_id){
                        $query->where('store_id','eq',$store_id);
                    }
                })->where($whereOne)
                ->with('user')
                ->order('create_time desc')
                ->select()->each(function ($item){
                    $item['product_order'] = ProductOrder::with('user')->where('id',$item['order_id'])->find();
                    $user = User::where('id',$item['user_id'])->find();
                    $item['store'] = Store::get($user['store_id']);
                    $item['store_user'] = null;
                })->toArray();
        }
    }
}